/**
 * 
 */
package com.edocbase.desktop.mht;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URLDecoder;
import java.util.concurrent.Callable;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.jsoup.Connection;
import org.jsoup.helper.HttpConnection;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.edocbase.desktop.mht.MHTCompiler.DownloadStatu;

/**
 * @author lifei114@gmail.com
 *
 */
class HTMLDownloadTask implements Callable<ResourceItem>{
	org.apache.log4j.Logger logger = org.apache.log4j.Logger
			.getLogger(HTMLDownloadTask.class);
	ResourceItem item = null;
	File outDir = null;
	int timeout = 1000 * 30;
	String contentCharset = null;
	MimeMultipart mainPart = null;
	HTMLDownloadTask(ResourceItem item,File outDir,int timeout,String contentCharset,MimeMultipart mainPart) {
		super();
		this.item = item;
		this.outDir = outDir;
		this.mainPart = mainPart;
		this.contentCharset = contentCharset;
	}

	public ResourceItem call() throws Exception {
		String saveLoc = item.shortUrl;
		String fileName = URLDecoder.decode(saveLoc, "UTF-8");
		saveLoc = fileName;
		File savepath = new File(outDir, fileName);
		String url = item.fullUrl;
		try {
			Connection conn = HttpConnection.connect(url);
			conn.header(
					"User-Agent",
					"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_1; zh-cn) AppleWebKit/531.22.7 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7");
			File dir = savepath.getParentFile();
			if (!dir.exists()){
				dir.mkdirs();
			}
			byte[] bytes = conn.timeout(timeout).execute().bodyAsBytes();
			FileOutputStream fos = new FileOutputStream(savepath);
			fos.write(bytes);
			fos.close();
			if (logger.isDebugEnabled()) {
				logger.debug("download success="+url);
			}
			item.downloadStatu = DownloadStatu.success;
			File resFile = new File(outDir, saveLoc);
			
			String path = java.net.URLDecoder.decode(saveLoc,
					contentCharset);
			path = MimeUtility.encodeText(path);
			MimeBodyPart bp = new MimeBodyPart();
			bp.addHeader("Content-Location", url);
			DataSource source = new FileDataSource(resFile);
			bp.setDataHandler(new DataHandler(source));
			mainPart.addBodyPart(bp);
		} catch (Exception e) {
			 e.printStackTrace(System.err);
			item.downloadStatu = DownloadStatu.fail;
			Elements els = item.doc.select("[src=" + saveLoc + "]");
			for (Element src : els) {
				String tagName = src.tagName();
				if (tagName.equals("img") || tagName.equals("script")
						|| tagName.equals("input")) {
					if (src.attr("src").equals(saveLoc)) {
						src.attr("src", url);
					}
				}
			}
		}

		return item;
	}
}
